package com.yuhang.learnandroid.chapter02.quiz

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.yuhang.learnandroid.R
import kotlinx.android.synthetic.main.activity_quiz2.*

class Quiz2Activity : AppCompatActivity() {
    private val TAG = "Quiz2Activity"
    private val KEY_INDEX="index"

    private val mQuestionBank: Array<Question> =
            arrayOf(
                    Question(R.string.q_oceans_text, true),
                    Question(R.string.q_mideast_text, false),
                    Question(R.string.q_africa_text, false),
                    Question(R.string.q_americas_text, true),
                    Question(R.string.q_asia_text,true))
    private var mCurrentIndex = 0

    override fun onSaveInstanceState(savedInstanceState: Bundle?) {
        super.onSaveInstanceState(savedInstanceState)
        Log.i(TAG, "onSaveInstanceState")
        savedInstanceState?.putInt(KEY_INDEX, mCurrentIndex)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate(Bundle) called!")
        setContentView(R.layout.activity_quiz2)

        if(savedInstanceState != null){
            mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0)
        }

        updateQuestion()


        previous_button.setOnClickListener{ v ->
            mCurrentIndex = (mQuestionBank.size + mCurrentIndex - 1) % mQuestionBank.size
            updateQuestion()
        }
        next_button.setOnClickListener{ v ->
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.size
            updateQuestion()
        }
        question_text_view.setOnClickListener{v ->
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.size
            updateQuestion()
        }

        true_button.setOnClickListener{ checkAnswer(true)}
        false_button.setOnClickListener{checkAnswer(false)}
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart() called!")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume() called!")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop() called!!")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy() called!!")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause() called!!")
    }

    private fun checkAnswer(pressedTrue: Boolean){
        val answerIsTrue = mQuestionBank[mCurrentIndex].mAnswearTrue

        var resId = if(pressedTrue == answerIsTrue) R.string.correct_toast else R.string.incorrect_toast

        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show()
    }

    private fun updateQuestion(){
        val q = mQuestionBank[mCurrentIndex].mTextResId
        question_text_view.setText(q)
    }
}
